﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Resources;
using System.Text;
using System.Windows;
using GBlason.Culture;
using GBlason.Properties;
using GBlason.ViewModel;
using GBlason.ViewModel.CoatOfArm;

namespace GBlason.Common.CustomCommand
{
    /// <summary>
    /// The command handling the changing of the coat of arms shape
    /// </summary>
    public class ChangeShapeCommand : CommandGeneric
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ChangeShapeCommand"/> class.
        /// </summary>
        /// <param name="ownertype">The ownertype.</param>
        public ChangeShapeCommand(Type ownertype)
            : base("Change shape", ownertype)
        {
        }

        private ShapeViewModel _oldShape;

        private ShapeViewModel _newShape;

        
        /// <summary>
        /// Does this instance.
        /// </summary>
        /// <param name="parameter"></param>
        public override void Do(CommandParameter parameter)
        {
            _newShape = parameter.Parameter as ShapeViewModel;

            if (_newShape == null)
                throw new ArgumentNullException("parameter");


            _oldShape = parameter.FileTargeted.RootCoatOfArm.CurrentShape;

            parameter.FileTargeted.RootCoatOfArm.CurrentShape = _newShape;

            Description = String.Format(CultureInfo.CurrentCulture,
                                        Resources.CommandDescChangeShape,
                                        _oldShape == null ? BlasonVocabulary.NoShape : _oldShape.LocalizedName,
                                        _newShape.LocalizedName
                );

            //sauvegarde, c'est affreux, je peux pas le faire dans la classe abstraite parceque c'est cette instance que je dois cloner :(
            //copie de code pour tous les execute !!
            Parameter = parameter;
            Done = true;
            parameter.FileTargeted.CommandsApplied.AddCommandHistory((ChangeShapeCommand)Clone());
        }

        public override void Redo()
        {
            Undo();
            Done = true;
        }

        /// <summary>
        /// Undoes this instance.
        /// Setting the old shape to the coat of arms
        /// </summary>
        public override void Undo()
        {
            var coaTarget = Parameter.FileTargeted.RootCoatOfArm;
            if (coaTarget == null) return;
            coaTarget.CurrentShape = _oldShape;
            _oldShape = _newShape;
            _newShape = coaTarget.CurrentShape;
            Done = false;
        }

        public override object Clone()
        {
            return MemberwiseClone();
        }
    }
}
